let app = getApp()
import wxcharts from '../../API/wxcharts.js' //引入
import { request } from "../../utils/request.js";
Page({

    data: {
        write_kind_list: [{
            word: '支出',
            choose: 1
        },
        {
            word: '收入',
            choose: 0
        }
        ],
        month: '',
        toMonth: '',
        year: '',
        toYear: '',
        pop_show: false,
        pop_show_to: false,
        currentDate: new Date().getTime(),
        maxDate: new Date().getTime(),
        minDate: 0,
        listForDay: [],
        income: 0,
        outcome: 0,
        income_list: [],
        outcome_list: [],
        zhuzhuangtuList_out: {},
        zhuzhuangtuList_in: {},
        configColor: app.globalData.configColor,
        configColorForOnlyStyle: app.globalData.configColorForOnlyStyle,
        ColorMost: app.globalData.ColorMost,
        ColorLess: app.globalData.ColorLess,
        paihangbangOut: [],
        paihangbangIn: [],
        hiddenCanvas: false,
        detail_show: false,
        selectedCategoryName: '',
        selectedMoney: '',
        selectedDate: '',
        selectedRemark: '',
        selectedUserName: '',
        dateCategroy: '单月',
        agvMoney: 0,
        monthCount: 0,
        agvMoneyABS: 0,
        financeData: [],
        statusBarHeight: app.globalData.statusBarHeight,
        navBarHeight: app.globalData.navBarHeight,
        totalJieYue: 0,
        warningOutList: [],
        warningInList: [],
        warnOutItem: null,
        warnInItem: null
    },
    // 支出或者入账
    choose_type(e) {
        if (this.selectComponent('#loginPopup').init()) {
            return
        }
        let that = this
        let write_kind_list = that.data.write_kind_list
        write_kind_list.forEach((item) => {
            item.choose = 0
        })
        let index = e.currentTarget.dataset.index * 1
        write_kind_list[index].choose = 1
        this.setData({
            write_kind_list
        })
        if (index == 0) {
            if (this.data.outcome_list == null || this.data.outcome_list.length <= 0) {
                return
            }
            if (this.data.zhuzhuangtuList_out == null || this.data.zhuzhuangtuList_out.length <= 0) {
                return
            }
            this.put_ring(true, this.data.outcome_list, app.globalData.ColorMost, '支出比', 'ringCanvas')
            // this.getday_per(this.data.zhuzhuangtuList_out, 1)
        }
        if (index == 1) {
            if (this.data.income_list == null || this.data.income_list.length <= 0) {
                return
            }
            if (this.data.zhuzhuangtuList_in == null || this.data.zhuzhuangtuList_in.length <= 0) {
                return
            }
            this.put_ring(false, this.data.income_list, app.globalData.ColorLess, '入账比', 'ringCanvass')
            // this.getday_per(this.data.zhuzhuangtuList_in, 0)
        }
    },
    // 关闭弹出
    onClose() {
        this.setData({
            pop_show: false,
            hiddenCanvas: false,
            detail_show: false,
            pop_show_to: false
        });
    },
    // 年月选择
    chooseDate(event) {
        let date = new Date(event.detail);
        let year = date.getFullYear();
        let month = date.getMonth() + 1;
        if (this.data.dateCategroy != '单月') {
            if (year > this.data.toYear || (year == this.data.toYear && month > this.data.toMonth)) {
                wx.showToast({
                    title: '请选择正确时间',
                    icon: 'none'
                })
                return
            }
        }
        // let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
        this.setData({
            pop_show: false,
            hiddenCanvas: false,
            year: year,
            month: month
        })
        if (this.data.dateCategroy == '单月') {
            app.globalData.cache_year_stc = date.getFullYear()
            app.globalData.cache_month_stc = date.getMonth() + 1
        }
        this.show()
    },
    chooseDateTo(event) {
        let date = new Date(event.detail);
        let toYear = date.getFullYear();
        let toMonth = date.getMonth() + 1;
        if (this.data.year > toYear || (this.data.year == toYear && this.data.month > toMonth)) {
            wx.showToast({
                title: '请选择正确时间',
                icon: 'none'
            })
            return
        }

        // let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
        this.setData({
            pop_show_to: false,
            hiddenCanvas: false,
            toYear: date.getFullYear(),
            toMonth: date.getMonth() + 1
        })
        app.globalData.cache_year_stc = date.getFullYear()
        app.globalData.cache_month_stc = date.getMonth() + 1
        this.show()
    },
    // 每日占比 生成柱状图
    // getday_per(item, isOut) {
    //     if (isOut == 1) {
    //         if (item.billVOList.length <= 0) {
    //             return
    //         }
    //         let dataForDay = []
    //         let categoriesForDay = []
    //         item.billVOList.forEach((item) => {
    //             dataForDay.push(item.outForDay)
    //             categoriesForDay.push(item.topTime)
    //         })
    //         new wxcharts({
    //             canvasId: 'columnCanvas',
    //             type: 'column',
    //             // categories: ['2012', '2013', '2014', '2015', '2016', '2017'],
    //             // series: [{
    //             //     data: [15, 20, 45, 37, 4, 80]
    //             //   }],
    //             categories: categoriesForDay,
    //             series: [{
    //                 data: dataForDay,
    //                 color: app.globalData.ColorMost
    //             }],
    //             yAxis: {
    //                 format: function (val) {
    //                     return '￥' + val;
    //                 }
    //             },
    //             extra: {
    //                 column: {
    //                     width: 15
    //                 }
    //             },
    //             width: 375,
    //             height: 200
    //         });
    //     }
    //     if (isOut == 0) {
    //         if (item.billVOList.length <= 0) {
    //             return
    //         }
    //         let dataForDay = []
    //         let categoriesForDay = []
    //         item.billVOList.forEach((item) => {
    //             dataForDay.push(item.inForDay)
    //             categoriesForDay.push(item.topTime)
    //         })
    //         new wxcharts({
    //             canvasId: 'columnCanvasForIn',
    //             type: 'column',
    //             // categories: ['2012', '2013', '2014', '2015', '2016', '2017'],
    //             // series: [{
    //             //     data: [15, 20, 45, 37, 4, 80]
    //             //   }],
    //             categories: categoriesForDay,
    //             series: [{
    //                 data: dataForDay,
    //                 color: app.globalData.ColorLess
    //             }],
    //             yAxis: {
    //                 format: function (val) {
    //                     return '￥' + val;
    //                 }
    //             },
    //             extra: {
    //                 column: {
    //                     width: 15
    //                 }
    //             },
    //             width: 375,
    //             height: 200
    //         });
    //     }
    // },
    // 生成饼图 this.put_ring(in_percentage,'#deb13c','入账比',ringCanvas)
    put_ring(isOut, list, color, word, id) {
        let series = []
        let currentColor = color
        list.forEach((item) => {
            let categoryName = item.categoryName
            let baifenbi = 0
            if (isOut) {
                baifenbi = (item.money / this.data.outcome) * 100
            } else {
                baifenbi = (item.money / this.data.income) * 100
            }

            let e = {
                name: categoryName,
                color: currentColor,
                data: baifenbi
            }
            currentColor = this.getLightColor(currentColor, 3)
            //   currentColor = this.getDarkColor(currentColor,3)
            series.push(e)
        })
        // console.log(series)
        new wxcharts({
            canvasId: id,
            type: 'ring',
            //   type: 'pie',
            series,
            width: 300,
            height: 300,
            title: {
                name: word,
                fontSize: 12,
                color: '#7f7f7f',
            },
            dataLabel: true,
        });
    },
    // 开启弹窗
    showPopup(e) {
        if (this.selectComponent('#loginPopup').init()) {
            return
        }
        if (e.currentTarget.dataset.isto == "0") {
            this.setData({
                hiddenCanvas: true,
                pop_show: true,
            });
        } else {
            this.setData({
                hiddenCanvas: true,
                pop_show_to: true,
            });
        }
    },
    //hex颜色转rgb颜色
    HexToRgb(str) {
        var r = /^\#?[0-9A-F]{6}$/;
        //test方法检查在字符串中是否存在一个模式，如果存在则返回true，否则返回false
        // if (!r.test(str)) return window.alert("输入错误的hex");
        //replace替换查找的到的字符串
        str = str.replace("#", "");
        //match得到查询数组
        var hxs = str.match(/../g);
        for (var i = 0; i < 3; i++) hxs[i] = parseInt(hxs[i], 16);
        return hxs;
    },
    //GRB颜色转Hex颜色
    RgbToHex(a, b, c) {
        var r = /^\d{1,3}$/;
        // if (!r.test(a) || !r.test(b) || !r.test(c)) return window.alert("输入错误的rgb颜色值");
        var hexs = [a.toString(16), b.toString(16), c.toString(16)];
        for (var i = 0; i < 3; i++) if (hexs[i].length == 1) hexs[i] = "0" + hexs[i];
        return "#" + hexs.join("");
    },
    //得到hex颜色值为color的加深颜色值，level为加深的程度，限1-10之间
    getDarkColor(color, level) {
        var r = /^\#?[0-9A-F]{6}$/;
        // if (!r.test(color)) return window.alert("输入错误的hex颜色值");
        var rgbc = this.HexToRgb(color);
        //floor 向下取整
        for (var i = 0; i < 3; i++) {
            // rgbc[i] = Math.floor(rgbc[i] * (1 - level/10))
            rgbc[i] = Math.floor(rgbc[i] - level * 5)
            if (rgbc[i] < 0) {
                rgbc[i] = 0
            }
        };
        return this.RgbToHex(rgbc[0], rgbc[1], rgbc[2]);
    },
    //得到hex颜色值为color的减淡颜色值，level为加深的程度，限0-1之间
    getLightColor(color, level) {
        var r = /^\#?[0-9A-F]{6}$/;
        // if (!r.test(color)) return window.alert("输入错误的hex颜色值");
        var rgbc = this.HexToRgb(color);
        for (var i = 0; i < 3; i++) {
            // rgbc[i] = Math.floor((255 - rgbc[i]) * level + rgbc[i])
            rgbc[i] = Math.floor(rgbc[i] + level * 5)
            if (rgbc[i] > 240) {
                rgbc[i] = 240
            }
        };
        return this.RgbToHex(rgbc[0], rgbc[1], rgbc[2]);
    },
    onTapAndOpenDetail(e) {
        if (this.selectComponent('#loginPopup').init()) {
            return
        }
        let detail = e.currentTarget.dataset.detail
        let money = ''
        if (detail.isOut) {
            money = detail.money + ' (支出)'
        } else {
            money = detail.money + ' (收入)'
        }
        this.setData({
            detail_show: true,
            selectedCategoryName: detail.categoryName,
            selectedMoney: money,
            selectedDate: detail.createTime,
            selectedRemark: detail.remark,
            selectedUserName: detail.username,
        })
    },
    changeDateCategroy() {
        if (this.selectComponent('#loginPopup').init()) {
            return
        }
        if (this.data.dateCategroy == '单月') {
            this.setData({
                dateCategroy: '至',
                toYear: this.data.year,
                toMonth: this.data.month
            })
        } else {
            this.setData({
                dateCategroy: '单月',
                year: this.data.toYear,
                month: this.data.toMonth
            })
            this.show();
        }
    },
    setPercentageColor(list, pay) {
        let isArr = Array.isArray(list)
        let tempList = []
        if(!isArr){
            tempList.push(list)
        }else{
            tempList = list
        }
        tempList.forEach(item=>{
            if (item.isOut) {
                item.percentageColor = "#F44336"
            } else {
                // if (item.percentage >= 31 && item.percentage <= 60) {
                //     item.percentageColor = pay ? this.getDarkColor(app.globalData.ColorMost, 3) : this.getDarkColor(app.globalData.ColorLess, 3)
                // } else if (item.percentage >= 61 && item.percentage <= 100) {
                //     item.percentageColor = pay ? this.getDarkColor(app.globalData.ColorMost, 8) : this.getDarkColor(app.globalData.ColorLess, 8)
                // } else {
                //     item.percentageColor = pay ? app.globalData.ColorMost : app.globalData.ColorLess
                // }
                if (item.percentage >= 51 && item.percentage <= 75) {
                    item.percentageColor = pay ? this.getDarkColor(app.globalData.ColorMost, 10) : this.getDarkColor(app.globalData.ColorLess, 10)
                } else if (item.percentage >= 76 && item.percentage <= 100) {
                    item.percentageColor = "#FF8C00"
                } else {
                    item.percentageColor = pay ? app.globalData.ColorMost : app.globalData.ColorLess
                }
            }
        })
        return isArr ? tempList : tempList[0]
    },
    show() {
        wx.showLoading({
            title: '',
        })
        // 分类预警
        request({
            url: "/getWarningCategory",
            method: 'Get',
            data: {
                userId: wx.getStorageSync('userInfo').id,
                year: this.data.year,
                month: this.data.month,
                groupId: wx.getStorageSync('userInfo').groupVO.id,
                toYear: this.data.toYear,
                toMonth: this.data.toMonth,
                dateCategroy: this.data.dateCategroy
            },
        }).then((responseData) => {
            this.setData({
                warnOutItem: this.setPercentageColor(responseData.warnOutSumVO, true),
                warnInItem: this.setPercentageColor(responseData.warnInSumVO, false),
                warningOutList: this.setPercentageColor(responseData.outCategory, true),
                warningInList: this.setPercentageColor(responseData.inCategory, false)
            })
        })
        // 饼图 + 分类统计 + 总支出 + 平均结余
        request({
            url: "/getBillGroupByCategory",
            method: "POST",
            header: {
                'content-type': 'application/json'
            },
            data: {
                userId: wx.getStorageSync('userInfo').id,
                year: this.data.year,
                month: this.data.month,
                groupId: wx.getStorageSync('userInfo').groupVO.id,
                toYear: this.data.toYear,
                toMonth: this.data.toMonth,
                dateCategroy: this.data.dateCategroy
            },
        }).then((responseData) => {
            if (responseData.length > 0 && responseData[0].groupByCategory.length > 0) {
                this.setData({
                    outcome_list: responseData[0].groupByCategory,
                    outcome: responseData[0].outForMonth
                })
                if (this.data.outcome_list.length) {
                    this.put_ring(true, this.data.outcome_list, app.globalData.ColorMost, '支出比', 'ringCanvas')
                }
            } else {
                this.setData({
                    outcome_list: [],
                    outcome: 0
                })
            }
            if (responseData.length > 0 && responseData[1].groupByCategory.length > 0) {
                this.setData({
                    income_list: responseData[1].groupByCategory,
                    income: responseData[1].inForMonth
                })
                if (this.data.income_list.length) {
                    this.put_ring(false, this.data.income_list, app.globalData.ColorLess, '入账比', 'ringCanvass')
                }
            } else {
                this.setData({
                    income_list: [],
                    income: 0
                })
            }
            // 总结余
            this.setData({
                totalJieYue: Math.abs(this.data.income - this.data.outcome).toFixed(2)
            })
            wx.hideLoading()
        })
        // 排行榜
        request({
            url: "/getTenBill",
            method: 'Get',
            data: {
                userId: wx.getStorageSync('userInfo').id,
                year: this.data.year,
                month: this.data.month,
                groupId: wx.getStorageSync('userInfo').groupVO.id,
                toYear: this.data.toYear,
                toMonth: this.data.toMonth,
                dateCategroy: this.data.dateCategroy
            },
        }).then((responseData) => {
            this.setData({
                paihangbangOut: responseData[0].billVOList,
                paihangbangIn: responseData[1].billVOList
            })
        })
        // 每月汇总
        request({
            url: "/getInfoForEveryMonth",
            method: 'Get',
            data: {
                userId: wx.getStorageSync('userInfo').id,
                year: this.data.year,
                month: this.data.month,
                groupId: wx.getStorageSync('userInfo').groupVO.id,
                toYear: this.data.toYear,
                toMonth: this.data.toMonth,
                dateCategroy: this.data.dateCategroy
            },
        }).then((responseData) => {
            this.setData({
                agvMoney: responseData.agvMoney,
                agvMoneyABS: Math.abs(responseData.agvMoney),
                monthCount: responseData.monthCount,
                financeData: responseData.billVOList
            })
        })
        // 柱状图
        // request({
        //     url: "/getBillGroupByTypeAndDay",
        //     method: 'POST',
        //     header: {
        //         'content-type': 'application/json'
        //     },
        //     data: {
        //         userId: wx.getStorageSync('userInfo').id,
        //         year: this.data.year,
        //         month: this.data.month,
        //         groupId: wx.getStorageSync('userInfo').groupVO.id,
        //         toYear: this.data.toYear,
        //         toMonth: this.data.toMonth,
        //         dateCategroy: this.data.dateCategroy
        //     },
        // }).then((responseData) => {
        //     if (responseData.length <= 0) {
        //         this.setData({
        //             income_list: [],
        //             outcome_list: [],
        //             outcome: 0,
        //             income: 0
        //         })
        //         wx.hideLoading()
        //         return
        //     }
        //     responseData.forEach((itemForOut) => {
        //         if (itemForOut.isOut == true || itemForOut.isOut == 'true') {
        //             this.setData({
        //                 zhuzhuangtuList_out: itemForOut
        //             })
        //         }
        //         if (itemForOut.isOut == false || itemForOut.isOut == 'false') {
        //             this.setData({
        //                 zhuzhuangtuList_in: itemForOut
        //             })
        //         }
        //     })
        //     this.getday_per(this.data.zhuzhuangtuList_out, 1)
        //     this.getday_per(this.data.zhuzhuangtuList_in, 0)
        // })
    },
    /**
       * 生命周期函数--监听页面显示
       */
    onShow() {
        if (this.selectComponent('#loginPopup').init()) {
            return
        }
        if (wx.getStorageSync('configColor') !== this.data.configColor
            || wx.getStorageSync('configColorForOnlyStyle') !== this.data.configColorForOnlyStyle
            || wx.getStorageSync('ColorMost') !== this.data.ColorMost
            || wx.getStorageSync('ColorLess') !== this.data.ColorLess) {
            this.setData({ configColor: wx.getStorageSync('configColor') });
            this.setData({ configColorForOnlyStyle: wx.getStorageSync('configColorForOnlyStyle') });
            this.setData({ ColorMost: wx.getStorageSync('ColorMost') });
            this.setData({ ColorLess: wx.getStorageSync('ColorLess') });
        }

        var flag = true;
        if (app.globalData.cache_year_stc > 0 && app.globalData.cache_month_stc > 0) {
            flag = false;
            this.setData({
                year: app.globalData.cache_year_stc,
                month: app.globalData.cache_month_stc,
                toYear: app.globalData.cache_year_stc,
                toMonth: app.globalData.cache_month_stc,
            })
        }
        // 获取最早+最晚记录时间
        wx.request({
            url: app.globalData.url + '/getDateRangeByGroup',
            method: 'POST',
            header: { 'content-type': 'application/json' },
            data: {
                groupIdList: [wx.getStorageSync('userInfo').groupVO.id]
            },
            success: (res) => {
                let responseData = res.data
                this.setData({
                    minDate: responseData.data.minDateStamp,
                    maxDate: responseData.data.maxDateStamp
                })
                if (flag) {
                    var date = new Date(responseData.data.maxDateStamp);
                    this.setData({
                        year: date.getFullYear(),
                        month: date.getMonth() + 1,
                        toYear: date.getFullYear(),
                        toMonth: date.getMonth() + 1,
                        currentDate: responseData.data.maxDateStamp
                    })
                    app.globalData.cache_year_stc = this.data.year
                    app.globalData.cache_month_stc = this.data.month
                } else {
                    this.setData({
                        currentDate: new Date(app.globalData.cache_year_stc + "/" + app.globalData.cache_month_stc).getTime()
                    })
                }
                this.show()
            },
            fail: (err) => {
                console.log('失败', err);
            }
        })

        this.setData({
            // this.getDarkColor(app.globalData.ColorMost,6)
            // this.getLightColor(app.globalData.ColorMost,6)
            // warnBarMostColor: this.getLightColor(app.globalData.ColorMost,6),
            // warnBigBarMostColor: app.globalData.ColorMost,
            // warnBarMostColor: app.globalData.ColorMost,
            // warnBigBarMostColor: this.getDarkColor(app.globalData.ColorMost, 6),
            // warnBarLessColor: app.globalData.ColorLess,
            // warnBigBarLessColor: this.getDarkColor(app.globalData.ColorLess, 6)
        })
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        wx.hideShareMenu({
            menus: ['shareAppMessage', 'shareTimeline']
        })
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})